package com.jubaozan.framework.sentinel.springmvc.config;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.redis.RedisDataSource;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jubaozan.framework.sentinel.config.ApplicationRedisValueConfig;
import com.jubaozan.framework.sentinel.constant.RuleKeyConstant;
import com.jubaozan.framework.sentinel.springmvc.listener.AuthorityRulePropertyListener;
import java.util.List;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/23 13:36
 */

@Slf4j
@Component
public class AuthorityRuleRedisDataSource extends BaseRedisDataSource{
    private  final  AuthorityRulePropertyListener authorityRulePropertyListener;

    public AuthorityRuleRedisDataSource(AuthorityRulePropertyListener authorityRulePropertyListener,
        ApplicationRedisValueConfig applicationRedisValueConfig, RuleKeyConstant ruleKeyConstant) {
         super(applicationRedisValueConfig,ruleKeyConstant);
        this.authorityRulePropertyListener = authorityRulePropertyListener;
    }


    @PostConstruct
    public void init() {
        log.info("init AuthorityRuleRedisDataSource");
        Converter<String, List<AuthorityRule>> ruleConfigParser = source -> JSON.parseObject(source, new TypeReference<List<AuthorityRule>>() {});
        ReadableDataSource<String, List<AuthorityRule>> redisDataSource = new RedisDataSource<>(config,
            ruleKeyConstant.getAuthorityRuleKey(), channel, ruleConfigParser);
        redisDataSource.getProperty().addListener(authorityRulePropertyListener);
        AuthorityRuleManager.register2Property(redisDataSource.getProperty());

    }
}
